from django.contrib import admin
from django import forms
from django.utils.html import format_html
from .models import ExchangeItem, ExchangeTransaction
from backed.cos_utils import cos_uploader


class ExchangeItemAdminForm(forms.ModelForm):
    image = forms.FileField(required=False)

    class Meta:
        model = ExchangeItem
        fields = ['user', 'title', 'description', 'image_url', 'category', 'city', 'status']


@admin.register(ExchangeItem)
class ExchangeItemAdmin(admin.ModelAdmin):
    """交换物品管理"""
    list_display = ['item_id', 'image_preview', 'user', 'title', 'category', 'city', 'status', 'created_at']
    list_filter = ['status', 'category', 'city', 'created_at']
    date_hierarchy = 'created_at'
    autocomplete_fields = ['user']
    search_fields = ['user__id', 'user__username', 'title', 'category', 'city']
    ordering = ['-created_at']
    list_per_page = 25
    form = ExchangeItemAdminForm

    fieldsets = [
        ('基本信息', {'fields': ['user', 'title', 'description', 'category', 'city', 'status']}),
        ('图片', {'fields': ['image_preview', 'image', 'image_url']})
    ]
    readonly_fields = ['image_preview']

    def image_preview(self, obj):
        if obj.image_url:
            return format_html('<img src="{}" style="width:50px;height:50px;object-fit:cover;border-radius:4px;border:1px solid #ddd;"/>', obj.image_url)
        return '无图片'
    image_preview.short_description = '图片'

    def save_model(self, request, obj, form, change):
        image = request.FILES.get('image')
        if image:
            if image.content_type in ['image/jpeg', 'image/png', 'image/gif', 'image/webp'] and image.size <= 10 * 1024 * 1024:
                result = cos_uploader.upload_file(image, file_type='exchange', user_id=(obj.user.id if obj.user else None))
                if result.get('success'):
                    obj.image_url = result.get('url')
        super().save_model(request, obj, form, change)


@admin.register(ExchangeTransaction)
class ExchangeTransactionAdmin(admin.ModelAdmin):
    """交换记录管理"""
    list_display = ['transaction_id', 'item', 'provider', 'receiver', 'completed_at']
    list_filter = ['completed_at']
    date_hierarchy = 'completed_at'
    autocomplete_fields = ['item', 'provider', 'receiver']
    search_fields = ['item__title', 'provider__username', 'receiver__username']
